package com.topvision.myviewtest.annotation;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import com.topvision.myviewtest.R;

import java.lang.reflect.Field;

/**
 * @author lucy
 * @date 2018-06-28 16:33
 * @description //TODO
 */

public class AnnotationActivity extends AppCompatActivity {

    @MyBindView(R.id.tv_annotation)
    TextView mTextView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_annotation);

        getAllAnnotationView();
        mTextView.setText("注解得到的TextView");
    }

    /**
     * 不可取的方式（运行时注解，耗时）
     */
    private void getAllAnnotationView() {
        Field[] fields = getClass().getDeclaredFields();
        try {
            for (Field field : fields) {
                // 判断注解
                if (field.getAnnotations() != null) {
                    // 确认注解类型
                    if (field.isAnnotationPresent(MyBindView.class)) {
                        // 允许反射修改
                        field.setAccessible(true);
                        MyBindView myBindView = field.getAnnotation(MyBindView.class);
                        field.set(AnnotationActivity.this, findViewById(myBindView.value()));
                    }
                }
            }
        } catch (Exception e) {

        }

    }
}
